package info.ask4research.service.impl;

import info.ask4research.dao.impl.UserDAO;
import info.ask4research.model.User;
import info.ask4research.util.Util;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
	
	private UserDAO userDAO;
	private Util util;

	/**
	 * Get all contacts
	 * @return
	 */
	@Transactional(readOnly=true)
	public List<User> getUserList(){

		return userDAO.getUsers();
	}
	
	/**
	 * Create new Contact/Contacts
	 * @param data - json data from request
	 * @return created contacts
	 */
	@Transactional
	public List<User> create(Object data){
		
        List<User> newUsers = new ArrayList<User>();
		
		List<User> list = util.getUsersFromRequest(data);
		
		for (User user : list){
			newUsers.add(userDAO.saveUser(user));
		}
		
		return newUsers;
	}
	
	
	/**
	 * Update contact/contacts
	 * @param data - json data from request
	 * @return updated contacts
	 */
	@Transactional
	public List<User> update(Object data){
		
		List<User> returnUsers = new ArrayList<User>();
		
		List<User> updatedUsers = util.getUsersFromRequest(data);
		
		for (User user : updatedUsers){
			returnUsers.add(userDAO.saveUser(user));
		}
		
		return returnUsers;
	}
	
	/**
	 * Update contact/contacts
	 * @param data - json data from request
	 * @return updated contacts
	 */
	@Transactional
	public User save(User user){
		
		return userDAO.saveUser(user);
		
	}
	
	
	/**
	 * Find by id
	 * @param data - json data from request
	 * @return updated contacts
	 */
	@Transactional
	public User get(int userId){
		
		return userDAO.get(userId);
		
	}
	
	/**
	 * Delete contact/contacts
	 * @param data - json data from request
	 */
	@Transactional
	public void delete(Object data){
		
		//it is an array - have to cast to array object
		if (data.toString().indexOf('[') > -1){
			
			List<Integer> deleteUsers = util.getListIdFromJSON(data);
			
			for (Integer id : deleteUsers){
				userDAO.deleteUser(id);
			}
			
		} else { //it is only one object - cast to object/bean
			
			Integer id = Integer.parseInt(data.toString());
			
			userDAO.deleteUser(id);
		}
	}
	
	/**
	 * Spring use - DI
	 * @param contactDAO
	 */
	@Resource(name="userDao")
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	/**
	 * Spring use - DI
	 * @param util
	 */
	@Autowired
	public void setUtil(Util util) {
		this.util = util;
	}

	public List<User> getUserByUsernameAndPassword(String username, String password) {
		return userDAO.getUserByUsernameAndPassword(username, password);
	}


	
}
